package zookeeper.curator.test3;

import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;

import java.util.concurrent.CountDownLatch;

/**
 *chapter 3 获取子节点内容(异步方式)
 *
 * Zookeeper提供了两个方法来获取节点内容，同步获取和异步获取：

 public byte[] getData(String path, boolean watch, Stat stat)

 public void getData(final String path, Watcher watcher,
 DataCallback cb, Object ctx)

 参数说明
 参数	说明
 path	指定数据节点的路径，获取该节点下面的子节点
 watcher	注册在path上的Watcher。节点变更会通知会向客户端发起通知。
 stat	指定数据节点状态信息。传入旧stat，方法执行过程中会将其替换为新stat对象。
 watch	表示是否需要注册一个watcher。true：注册默认watcher，false：不需要注册watcher
 cb	注册一个异步回调函数
 ctx	传递上下文信息
 * Created by majian8 on 2018/6/18.
 */
public class TestGetData2 implements Watcher{
    private static CountDownLatch countDownLatch = new CountDownLatch(1);

    private static ZooKeeper zooKeeper;
    private static Stat stat = new Stat();

    public static void main(String[] args) throws Exception{
        zooKeeper = new ZooKeeper("192.168.209.128:2181", 5000, new TestGetData());
        countDownLatch.await();

        String path = "/datatest2";
        zooKeeper.create(path,"123".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
        // 异步读取节点内容
        zooKeeper.getData(path,true,new MyDataCallback(),null);

        zooKeeper.setData(path,"123".getBytes(),-1);

        Thread.sleep(10000);
    }
    @Override
    public void process(WatchedEvent event) {
        if (Event.KeeperState.SyncConnected == event.getState()) {
            if(Event.EventType.None == event.getType() && null == event.getPath()){ // 连接时的监听事件
                countDownLatch.countDown();
            } else if (event.getType() == Event.EventType.NodeDataChanged){ // 子节点内容变更时的监听
                try {
                    System.out.println("监听获得通知内容：data="
                            + new String(zooKeeper.getData(event.getPath(),true,stat)));
                    System.out.println("监听获得通知Stat：czxid=" + stat.getCzxid()
                            + ";mzxid=" + stat.getMzxid() + ";version="  + stat.getVersion());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

class MyDataCallback implements AsyncCallback.DataCallback{
    @Override
    public void processResult(int rc, String path, Object ctx, byte[] data, Stat stat) {
        System.out.println("异步返回结果：rc=" + rc + ";path=" + path + ";data=" + new String(data));
        System.out.println("异步读取Stat：czxid=" + stat.getCzxid()
                + ";mzxid=" + stat.getMzxid() + ";version="  + stat.getVersion());
    }
}